//
//  OrderDetailBaseVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/29.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Moya
import Kingfisher

enum OrderDetailType: String {
  case untreated // 待抢
  case accepted  // 我的处理中的详情
  case finish // 完结工单
}

class OrderDetailBaseVC: BaseVC {
  
  var parentVC: UIViewController?
  var orderId: String!
  var orderStatus: OrderDetailType!
    var refreshBeforeClosure: VoidClosure?
  
  fileprivate var detailModel: OrderDetailModel?
  fileprivate var tableView: UITableView!
  fileprivate var getButton: UIButton?
  fileprivate var replyV: ReplyV?
  fileprivate var cancle: Cancellable?
    fileprivate var firstHeight: CGFloat = 0
  
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = GlobalConfig.BGWhiteColor
    
    create()
    pullData(with: true)
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    parentVC?.navigationController?.navigationBar.setBackgroundImage(GlobalConfig.BGWhiteImage, for: .default)
    
//    if .accepted == self.orderStatus { parentVC?.navigationController?.setToolbarHidden(false, animated: false) }
//    if let temp = detailModel{
//        if .untreated == self.orderStatus && temp.isCanGetOrder {parentVC?.navigationController?.setToolbarHidden(false, animated: false)}
//    }
        GlobalConfig.baiduStatisticsPageViewStart("工单详情")
  }
  
  override func viewWillDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    if let temp = cancle { temp.cancel() }
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        navigationController?.setToolbarHidden(true, animated: false)
        GlobalConfig.baiduStatisticsPageViewEnd("工单详情")
    }
  
  deinit {
    replyV?.removeFromSuperview()
  }

}

// MARK: - action

extension OrderDetailBaseVC {
  
  fileprivate func closure() {
    
    // 转交
    replyV?.sendOnClosure = { [unowned self] in
      let vc = SelectEmployeeVC()
      vc.orderId = self.detailModel?.id ?? ""
      
      vc.didSuccess = { [unowned self] in
        self.pullData(with: false)
      }
      self.refreshBeforeClosure?()
      self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // 回复
    replyV?.replyClosure = { [unowned self] in
      let vc = ReplyVC()
      vc.orderId = self.detailModel?.id ?? ""
      
      vc.didSuccess = { [unowned self] in
        self.pullData(with: false)
      }
      
      self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // 完结
    replyV?.finishClosure = { [unowned self] in
      
      let finishPop = TipPopV(frame: UIScreen.main.bounds, type: .finish)
      finishPop.show(in: self.navigationController!.view)
      
      finishPop.confirmClosure = { [unowned self] in
        
        SJApp.showHUD()
        let _ = WorkorderRequest.shared.handleOrder(type: "FINISH", workOrderId: self.detailModel!.id, staffId: "", replyContent: "", images: "", success: { 
          SJToast.successShow("完结工单成功!")
          
          self.pullData(with: false)
            self.refreshBeforeClosure?()
          self.navigationController?.setToolbarHidden(true, animated: true)
        }, failure: {  })
  
        
      }
      
    }
  }
}

// MARK: - fileprivate

extension OrderDetailBaseVC {
  
  fileprivate func pullData(with hud: Bool) {
  
    SJApp.showClearHUD()
    
    cancle = WorkorderRequest.shared.getOrderDetail(id: orderId, success: { (model) in
        self.detailModel = model
        self.createByResultData()
        
        runOnMainThread {
            self.tableView.reloadData()
        }
      
    })
  }
  
  fileprivate func create() {
    addBackItem()
    
    tableView = UITableView(frame:CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight))
    tableView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(OrderTitleCell.self, forCellReuseIdentifier: OrderTitleCell.identifier)
    tableView.register(DetailInfoCell.self, forCellReuseIdentifier: DetailInfoCell.identifier)
    tableView.register(ImageShowCell.self, forCellReuseIdentifier: ImageShowCell.identifier)
    tableView.register(SponsorInfoCell.self, forCellReuseIdentifier: SponsorInfoCell.identifier)
    tableView.register(TagsCell.self, forCellReuseIdentifier: TagsCell.identifier)
    tableView.register(TimeCell.self, forCellReuseIdentifier: TimeCell.identifier)
    tableView.register(CommentCell.self, forCellReuseIdentifier: CommentCell.identifier)
    tableView.separatorStyle = .none
    
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableFooterView = footerView
    
    view.addSubview(tableView)
  }
  
  fileprivate func createGetOrder() {
    
    tableView.sj.height = UIScreen.height - UIScreen.navBarHeight - 60 - UIScreen.iPhoneX_bottom
    
    getButton = UIButton(frame: CGRect(x: 10, y:tableView.sj.bottom, width: UIScreen.width - 20, height: 50))
    getButton?.setTitle("接单", for: .normal)
    getButton?.setTitleColor(UIColor.white, for: .normal)
    getButton?.setBackgroundImage(UIImage.getLinerGradientImage(with: UIColor.hex("#2D96F1"), endColor: UIColor.hex("#04BEFE"), size: CGSize(width: UIScreen.width, height: 50)), for: .normal)
    getButton?.layer.cornerRadius = 4
    getButton?.clipsToBounds = true
    getButton?.addTarget(self, action: #selector(getOrderAction), for: .touchUpInside)
    self.view.addSubview(getButton!)
  }
  
  fileprivate func createMyReplyOrder(style: ReplyVStyle) {
    view.backgroundColor = UIColor.white
    tableView.sj.height = UIScreen.height - UIScreen.navBarHeight - 44 - UIScreen.iPhoneX_bottom
    tableView.register(OrderReplyCell.self, forCellReuseIdentifier: OrderReplyCell.identifier)
    
    replyV = ReplyV(frame: CGRect(x: 0, y: tableView.sj.bottom, width: UIScreen.width, height: 44))
    replyV?.style = style
    self.view.addSubview(replyV!)
    closure()
  }
  
  func createByResultData() {
    // 因为要刷新界面先移除
    if let _ = replyV?.superview { replyV!.removeFromSuperview() }
    if let _ = getButton?.superview { getButton!.removeFromSuperview() }
    
    guard let temp = detailModel else { return }
    
    if "FINISHED" == temp.status {
      self.orderStatus = .finish
      tableView.sj.height = UIScreen.noNavBarHeight
      tableView.register(OrderReplyCell.self, forCellReuseIdentifier: OrderReplyCell.identifier)
    }
    else if "ACCEPTED" == temp.status {
      self.orderStatus = .accepted
      // 我的已接工单
      if temp.staffId == User.staffId { createMyReplyOrder(style: .other) }
      // 别人的已接工单
      else { createMyReplyOrder(style: .onlyReply) }
    }
    // 待接
    else if "UNTREATED" == temp.status {
      self.orderStatus = .untreated
        if detailModel!.isCanGetOrder {
            createGetOrder()
        }
        else {
            createMyReplyOrder(style: .onlyReply)
        }
    }
    
  }
  
}

// MARK: - action

extension OrderDetailBaseVC {
  
  @objc fileprivate func getOrderAction() {
    
    SJApp.showHUD()
    let _ = WorkorderRequest.shared.handleOrder(type: "ACCEPTED", workOrderId: detailModel!.id, staffId: "", replyContent: "", images: "", success: {
        self.pullData(with: false)
        self.refreshBeforeClosure?()
        SJToast.successShow("接单成功")
    }) { }
  
    
  }
  
}

// MARK: - UITableViewDataSource

extension OrderDetailBaseVC : UITableViewDataSource {
  
  func numberOfSections(in tableView: UITableView) -> Int {
      guard let model = detailModel else { return 0 }
      return model.sectionCount + 1
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    if 0 == section {
      guard let model = detailModel else { return 0 }
      return model.cellCount
    }
    else if 1 == section { return 1 }
    else if 2 == section {
      guard let model = detailModel else { return 0 }
      return model.records.count
    }
    
    return 0
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if 0 == indexPath.section {
      switch indexPath.row {
      case 0:
        
        let cell = tableView.dequeueReusableCell(withIdentifier: OrderTitleCell.identifier) as! OrderTitleCell
        cell.model = detailModel
        return cell
        
      case 1:
        let cell = tableView.dequeueReusableCell(withIdentifier: DetailInfoCell.identifier) as! DetailInfoCell
        cell.model = detailModel
        return cell
      default:
        break
      }
      
      guard let model = detailModel else { fatalError() }
      
      // 附件发起人只有其中一个
      if 4 == model.cellCount {
        // 只有附件
        if model.isImages {
          let cell = tableView.dequeueReusableCell(withIdentifier: ImageShowCell.identifier) as! ImageShowCell
          cell.models = detailModel?.thumbImageURLs ?? []
          return cell
        }
        // 只有发起人
        else {
          if 2 == indexPath.row {
            let cell = tableView.dequeueReusableCell(withIdentifier: SponsorInfoCell.identifier) as! SponsorInfoCell
            cell.model = detailModel
            return cell
          }
          else if 3 == indexPath.row {
            let cell = tableView.dequeueReusableCell(withIdentifier: TagsCell.identifier) as! TagsCell
            cell.titles = detailModel?.tags ?? []
            return cell
          }
        }
      }
      
      // 都有
      if 2 == indexPath.row {
        let cell = tableView.dequeueReusableCell(withIdentifier: ImageShowCell.identifier) as! ImageShowCell
        cell.models = detailModel?.thumbImageURLs ?? []
        
        cell.cellDidClick = { [unowned self] (index, collectionView) in
            guard let temps = self.detailModel?.images else {
                return
            }
            
            var images: [SJImageModel] = []
            for (index, item) in temps.enumerated() {
                if let cell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as? ImageSelectCell {
                    let image = SJImageModel(thumb: cell.imageV, thumb: cell.imageV.image, original: item.accessUrl)
                    images.append(image)
                }
                else {
                    let image = SJImageModel(thumb: nil, thumb: nil, original: item.accessUrl)
                    images.append(image)
                }
            }
            
            let viewer = ImageViewer(images: images, presentingVC: self)
            viewer.show(index: index)
        }
        return cell
      }
      else if 3 == indexPath.row {
        let cell = tableView.dequeueReusableCell(withIdentifier: SponsorInfoCell.identifier) as! SponsorInfoCell
        cell.model = detailModel
        return cell
      }
      else if 4 == indexPath.row {
        let cell = tableView.dequeueReusableCell(withIdentifier: TagsCell.identifier) as! TagsCell
        cell.titles = detailModel?.tags ?? []
        return cell
      }
    }
    else if 1 == indexPath.section {
      let cell = tableView.dequeueReusableCell(withIdentifier: TimeCell.identifier) as! TimeCell
      cell.time = detailModel?.createTime ?? ""
      return cell
    }
    else if 2 == indexPath.section {
      let cell = tableView.dequeueReusableCell(withIdentifier: CommentCell.identifier) as! CommentCell
        cell.row = indexPath.row
      cell.model = detailModel?.records[indexPath.row]
      cell.cellDidSelect = { [unowned self] (imageViews, index) in
            guard let temps = self.detailModel?.records[indexPath.row].images else {
                return
            }
            
            var images: [SJImageModel] = []
            for (index, item) in temps.enumerated() {
                let image = SJImageModel(thumb: imageViews[index], thumb: imageViews[index].image, original: item.accessUrl)
                images.append(image)
            }
            
            let viewer = ImageViewer(images: images, presentingVC: self)
            viewer.show(index: index)
        }
      return cell
    }
    
   return UITableViewCell()
  }
}

// MARK: - UITableViewDelegate

extension OrderDetailBaseVC : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let model = detailModel else { return 0 }
        
        if 0 == indexPath.section {
            switch indexPath.row {
              case 0:
                firstHeight = OrderTitleCell.heightWithTitle(title: detailModel?.title ?? "")
                return firstHeight
              case 1: return DetailInfoCell.height(with: detailModel?.content ?? "")
              default: break
            }
          
            // 附件发起人只有其中一个
            if 4 == model.cellCount {
                // 只有附件
                if model.isImages {
                    if model.images.count <= 4 { return (UIScreen.width - 80) / 4 + 90 }
                    else { return (UIScreen.width - 80) / 2 + 100 }
                }
                // 只有发起人
                else {
                    if 2 == indexPath.row { return SponsorInfoCell.height(with: detailModel?.houseAddress ?? []) }
                    else if 3 == indexPath.row {
                        let height = TagsCell.height(with: detailModel?.tags ?? [])
                        return height
                    }
                }
            }
          
                // 都有
                if 2 == indexPath.row {
                    if model.images.count <= 4 { return (UIScreen.width - 80) / 4 + 90 }
                    else { return (UIScreen.width - 80) / 2 + 100 }
                }
                else if 3 == indexPath.row {
                    return SponsorInfoCell.height(with: detailModel?.houseAddress ?? [])
                }
                else if 4 == indexPath.row {
                    let height = TagsCell.height(with: detailModel?.tags ?? [])
                    return height
                }
          
        }
        else if 1 == indexPath.section { return TimeCell.height }
        else if 2 == indexPath.section { return CommentCell.height(with: detailModel!.records[indexPath.row], row: indexPath.row) }

        return 0
    }
  
}
extension OrderDetailBaseVC : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > firstHeight - 34 {
            self.title = detailModel?.title
        } else {
            self.title = ""
        }
    }
}
